<template>
  <div class="loginFrom">
    <el-form
      ref="loginFormRef"
      :model="loginFormData"
      :rules="loginRules"
      size="large"
      :validate-on-rule-change="false"
    >
      <!-- 用户名 -->
      <el-form-item prop="username">
        <el-input v-model.trim="loginFormData.username" placeholder="请输入账号">
          <template #prefix>
            <img src="@/assets/images/log0.png" alt="" class="icon" />
          </template>
        </el-input>
      </el-form-item>

      <!-- 密码 -->
      <el-tooltip :visible="isCapsLock" :content="t('login.capsLock')" placement="right">
        <el-form-item prop="password" class="mb-0!">
          <el-input
            v-model.trim="loginFormData.password"
            :placeholder="t('login.password')"
            type="password"
            show-password
            @keyup="checkCapsLock"
            @keyup.enter="handleLoginSubmit"
          >
            <template #prefix>
              <img src="@/assets/images/log1.png" alt="" class="icon" />
            </template>
          </el-input>
        </el-form-item>
      </el-tooltip>

      <div class="flex-x-end w-full">
        <el-checkbox v-model="loginFormData.rememberMe">记住密码</el-checkbox>
      </div>

      <!-- 登录按钮 -->
      <el-form-item class="mb-0!">
        <el-button :loading="loading" type="primary" class="w-full" @click="handleLoginSubmit">
          立即登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import type { FormInstance } from "element-plus";
import AuthAPI, { type LoginFormData } from "@/api/auth-api";
import router from "@/router";
import { useUserStore } from "@/store";
import CommonWrapper from "@/components/CommonWrapper/index.vue";
import { AuthStorage } from "@/utils/auth";

const { t } = useI18n();
const userStore = useUserStore();
const route = useRoute();

const loginFormRef = ref<FormInstance>();
const loading = ref(false);
// 是否大写锁定
const isCapsLock = ref(false);
// 验证码图片Base64字符串
const captchaBase64 = ref();
// 记住我
const rememberMe = AuthStorage.getRememberMe();

const loginFormData = ref<LoginFormData>({
  username: "admin",
  password: "123456",
  captchaKey: "",
  captchaCode: "",
  rememberMe,
});

const loginRules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.username.required"),
      },
    ],
    password: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.password.required"),
      },
      {
        min: 6,
        message: t("login.message.password.min"),
        trigger: "blur",
      },
    ],
    captchaCode: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.captchaCode.required"),
      },
    ],
  };
});

// 获取验证码
const codeLoading = ref(false);

/**
 * 登录提交
 */
import { AuthStorage } from "@/utils/auth";
async function handleLoginSubmit() {
  // const redirectPath = (route.query.redirect as string) || "/";
  // router.push(decodeURIComponent(redirectPath));
  try {
    // 1. 表单验证
    const valid = await loginFormRef.value?.validate();
    if (!valid) return;
    loading.value = true;
    // 2. 执行登录
    await userStore.login(loginFormData.value);
    const redirectPath = (route.query.redirect as string) || "/";
    await router.push(decodeURIComponent(redirectPath));
  } catch (error) {
    // 4. 统一错误处理
    console.error("登录失败:", error);
  } finally {
    loading.value = false;
  }
}

// 检查输入大小写
function checkCapsLock(event: KeyboardEvent) {
  // 防止浏览器密码自动填充时报错
  if (event instanceof KeyboardEvent) {
    isCapsLock.value = event.getModifierState("CapsLock");
  }
}

const emit = defineEmits(["update:modelValue"]);
function toOtherForm(type: "register" | "resetPwd") {
  emit("update:modelValue", type);
}
</script>

<style lang="scss" scoped>
.loginFrom {
  :deep(.el-input) {
    height: 5.25rem;
    font-family:
      PingFang SC,
      PingFang SC;
    font-weight: 400;
    font-size: 1.5rem;
    color: #1d2129;
    .el-input__wrapper {
      background-color: #edf1fc;
    }
  }
  :deep(.el-form-item) {
    margin-bottom: 2.125rem;
    .el-button {
      height: 5.0625rem;
      font-family:
        PingFang SC,
        PingFang SC;
      font-weight: bold;
      font-size: 1.875rem;
      color: #ffffff;
      margin-top: 10.375rem;
    }
  }
  .icon {
    width: 2rem;
    margin-right: 1.0625rem;
  }
}
</style>
